from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QTableWidget, QTableWidgetItem, 
                             QHeaderView, QLabel)
from PyQt6.QtCore import Qt
from com.db.scan_record_price_analysis_manager import ScanRecordPriceAnalysisManager
from datetime import datetime
import json

class PriceAnalysisHistoryDialog(QDialog):
    def __init__(self, goods_id, parent=None):
        super().__init__(parent)
        self.goods_id = goods_id
        self.manager = ScanRecordPriceAnalysisManager()
        self.setup_ui()
        self.load_data()
        
    def setup_ui(self):
        """设置UI"""
        self.setWindowTitle(f"商品 {self.goods_id} 的历史分析数据")
        self.setMinimumSize(800, 600)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 创建表格
        self.table = QTableWidget()
        self.table.setColumnCount(7)
        self.table.setHorizontalHeaderLabels([
            "分析时间", "历史最低价", "普通售价", "常见售价", 
            "在售数量", "异常低价", "价格分布"
        ])
        
        # 设置表格列宽
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
        header.setSectionResizeMode(5, QHeaderView.ResizeMode.Stretch)
        header.setSectionResizeMode(6, QHeaderView.ResizeMode.Stretch)
        
        layout.addWidget(self.table)
        
    def load_data(self):
        """加载数据"""
        history = self.manager.get_analysis_history_all(self.goods_id)
        if not history:
            self.table.setRowCount(1)
            no_data = QTableWidgetItem("暂无历史数据")
            no_data.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            self.table.setSpan(0, 0, 1, 7)
            self.table.setItem(0, 0, no_data)
            return
            
        self.table.setRowCount(len(history))
        for row, record in enumerate(history):
            # 分析时间
            analysis_time = record['analysis_time']
            if isinstance(analysis_time, str):
                analysis_time = datetime.fromisoformat(analysis_time.replace('Z', '+00:00'))
            time_item = QTableWidgetItem(analysis_time.strftime('%Y-%m-%d %H:%M:%S'))
            self.table.setItem(row, 0, time_item)
            
            # 历史最低价
            if record.get('historical_low'):
                low_item = QTableWidgetItem(f"{record['historical_low']:.2f}元")
            else:
                low_item = QTableWidgetItem("-")
            self.table.setItem(row, 1, low_item)
            
            # 普通售价
            if record.get('normal_price'):
                normal_item = QTableWidgetItem(f"{record['normal_price']:.2f}元")
            else:
                normal_item = QTableWidgetItem("-")
            self.table.setItem(row, 2, normal_item)
            
            # 常见售价
            if record.get('common_sell_price'):
                common_item = QTableWidgetItem(f"{record['common_sell_price']:.2f}元")
            else:
                common_item = QTableWidgetItem("-")
            self.table.setItem(row, 3, common_item)
            
            # 在售数量
            count_item = QTableWidgetItem(str(record.get('selling_count', '-')))
            self.table.setItem(row, 4, count_item)
            
            # 异常低价
            abnormal_prices = record.get('abnormal_prices', [])
            if isinstance(abnormal_prices, str):
                abnormal_prices = json.loads(abnormal_prices)
            if abnormal_prices:
                prices = [f"{p['price']}元({p['count']}个)" for p in abnormal_prices]
                abnormal_item = QTableWidgetItem("，".join(prices))
            else:
                abnormal_item = QTableWidgetItem("无")
            self.table.setItem(row, 5, abnormal_item)
            
            # 价格分布
            price_distribution = record.get('price_distribution', {})
            if isinstance(price_distribution, str):
                price_distribution = json.loads(price_distribution)
            if price_distribution:
                dist_texts = []
                for price, count in price_distribution.items():
                    dist_texts.append(f"{price}元: {count}个")
                dist_item = QTableWidgetItem("，".join(dist_texts))
            else:
                dist_item = QTableWidgetItem("-")
            self.table.setItem(row, 6, dist_item)
